﻿using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
using DAL;

namespace WinForm.Common
{
    public struct FileStruct
    {
        /// <summary>  
        /// 是否为目录  
        /// </summary>  
        public bool IsDirectory { get; set; }
        /// <summary>  
        /// 创建时间  
        /// </summary>  
        public DateTime CreateTime { get; set; }
        /// <summary>  
        /// 文件或目录名称  
        /// </summary>  
        public string Name { get; set; }
        /// <summary>  
        /// 路径  
        /// </summary>  
        public string Path { get; set; }
    }
    class FtpHelper
    {

        private static string FtpServer
        {
            get { return ConfigInfo.Instance.FtpServer; }
        }
        private static string FtpUserName
        {
            get { return ConfigInfo.Instance.FtpUserId; }
        }
        private static string FtpPassword
        {
            get { return ConfigInfo.Instance.FtpPassword; }
        }
       

        /// <summary>
        /// 上传文件夹中以地市分组的所有文件
        /// </summary>
        /// <param name="folderDirectory">要上传的文件夹的本地绝对路径</param>
        /// <param name="remoteFolderName">ftp中的文件夹名字</param>
        public static bool UpLoad(string folderDirectory, string remoteFolderName)
        {
           

            /*------------------*/
            //UploadFile(@"G:/北京北京.mp3", @"三门峡/四六级考试/1.MP3");


            DirectoryInfo folder = new DirectoryInfo(folderDirectory);
            foreach (DirectoryInfo file in folder.GetDirectories())
            {
                //Get  remoteFolderName
                var remoteBaseFolderName = City.SelectByName(file.Name)[0].CetFtpDirectory;

                var subFolder = new DirectoryInfo(file.FullName);
                foreach (FileInfo item in subFolder.GetFiles())
                {
                    var remoteFolderFullName = string.Format(@"{0}/{1}", remoteBaseFolderName, remoteFolderName);
                    FtpCheckDirectoryExist(remoteFolderFullName);
                    
                    var remoteFileName = string.Format(@"{0}/{1}", remoteFolderFullName, item.Name);
                    UploadFile(item.FullName, remoteFileName);
                        
                    
                    
                    
                }
            }
            /*------------------*/

            
            
            return true;
        }
        public static int UploadFile(string localFilePath, string remoteFileName)
        {
            FileInfo fileInf = new FileInfo(localFilePath);
            string uri = "ftp://" + FtpServer + "/" + remoteFileName;
            FtpWebRequest reqFTP;

            // 根据uri创建FtpWebRequest对象 
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(FtpUserName, FtpPassword);

            // 默认为true，连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;

            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // 指定数据传输类型
            reqFTP.UseBinary = true;

            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;

            // 缓冲大小设置为2kb
            int buffLength = 2048;

            byte[] buff = new byte[buffLength];
            int contentLen;

            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();

                // 每次读文件流的2kb
                contentLen = fs.Read(buff, 0, buffLength);

                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);

                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // 关闭两个流
                strm.Close();
                fs.Close();
                return 0;
                ;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, @"Upload Error");
                return -1;
            }
        }

        //判断目录是否，不存创建
        public static bool FtpCheckDirectoryExist(string destFilePath)
        {
             try
            {
                string url = "ftp://" + FtpServer;
                Uri uri = new Uri(url + "/" + destFilePath);
                FtpWebRequest FTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                FTP.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
                FTP.Proxy = null;
                FTP.KeepAlive = false;
                FTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FTP.UseBinary = true;
                FtpWebResponse response = FTP.GetResponse() as FtpWebResponse;
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        

        ////创建目录   
        //public static Boolean FtpMakeDir(string localFile)
        //{
        //    FtpWebRequest req = (FtpWebRequest)WebRequest.Create(FtpServer + localFile);
        //    req.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
        //    req.Method = WebRequestMethods.Ftp.MakeDirectory;
        //    try
        //    {
        //        FtpWebResponse response = (FtpWebResponse)req.GetResponse();
        //        response.Close();
        //    }
        //    catch (Exception)
        //    {
        //        req.Abort();
        //        return false;
        //    }
        //    req.Abort();
        //    return true;

        //}   


    }
}
